//
//  SignalAssistorDetailEditViewController.m
//  Portable Traffic Signal Assistor
//
//  Created by Hao Xu on 4/1/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "SignalAssistorDetailEditViewController.h"

@interface SignalAssistorDetailEditViewController ()

@end

@implementation SignalAssistorDetailEditViewController
@synthesize phaseOffSetText = _phaseOffSetText;

static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 260;//216
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;


static const int TIMING_RING1_GRAPH_INITIAL_POSITION_X=10;
static const int TIMING_RING1_GRAPH_POSITION_Y=150;
static const int TIMING_RING1_GRAPH_HEIGHT=20;
static const int TIMING_RING2_GRAPH_INITIAL_POSITION_X=10;
static const int TIMING_RING2_GRAPH_POSITION_Y=180;
static const int TIMING_RING2_GRAPH_HEIGHT=20;



@synthesize signalNameTextField=_signalNameTextField;
@synthesize signalCycleLengthField=_signalCycleLengthField;
@synthesize cycleTimerLabel=_cycleTimerLabel;
@synthesize ring1TimerLabel=_ring1TimerLabel;
//@synthesize ring1TimerLabel = _ring1TimerLabel;
@synthesize ring2TimerLabel=_ring2TimerLabel;
//@synthesize ring2TimerLabel = _ring2TimerLabel;
@synthesize phaseNoInputTextField=_phaseNoInputTextField;
//@synthesize phaseNoInputTextField = _phaseNoInputTextField;
@synthesize phaseMovementInputTextField=_phaseMovementInputTextField;
//@synthesize phaseMovementInputTextField = _phaseMovementInputTextField;
@synthesize phaseRingInputTextField=_phaseRingInputTextField;
//@synthesize phaseRingInputTextField = _phaseRingInputTextField;
@synthesize phaseGreenInputTextField=_phaseGreenInputTextField;
//@synthesize phaseGreenInputTextField = _phaseGreenInputTextField;
@synthesize phaseYellowInputTextField=_phaseYellowInputTextField;
//@synthesize phaseYellowInputTextField = _phaseYellowInputTextField;
@synthesize phaseAllRedInputTextField=_phaseAllRedInputTextField;
@synthesize signalOffsetTextField = _signalOffsetTextField;
//@synthesize phaseYellowInputTextField = _phaseYellowInputTextField;
@synthesize addNewPhaseButton=_addNewPhaseButton;
@synthesize removePhaseButton = _removePhaseButton;
@synthesize savePhaseEditButton = _savePhaseEditButton;
@synthesize offsetPhaseLabel = _offsetPhaseLabel;
@synthesize mapButton = _mapButton;
//@synthesize addNewPhaseButton = _addNewPhaseButton;

//@synthesize timerGroupID=_timerGroupID;
//@synthesize signalID=_signalID;
@synthesize timingPattern=_timingPattern;
@synthesize subSystem=_subSystem;
@synthesize agency=_agency;
@synthesize signal=_signal;
@synthesize timingRing1GraphPositionX=_timingRing1GraphPositionX;
@synthesize timingRing2GraphPositionX=_timingRing2GraphPositionX;
@synthesize timer=_timer;
@synthesize ring1LabelList=_ring1LabelList;
@synthesize ring2LabelList=_ring2LabelList;
@synthesize labelList=_labelList;
@synthesize textFieldList=_textFieldList;
@synthesize beginOrEndArray=_beginOrEndArray;
@synthesize phasePicker = _phasePicker;
@synthesize selectedPhase=_selectedPhase;
//@synthesize picker=_picker;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void) dealloc
{
    [_signalNameTextField release];
    [_signalCycleLengthField release];
    [_cycleTimerLabel release];
    [_ring1TimerLabel release];
    [_ring2TimerLabel release];
    [_phaseNoInputTextField release];
    [_phaseMovementInputTextField release];
    [_phaseRingInputTextField release];
    [_phaseGreenInputTextField release];
    [_phaseYellowInputTextField release];
    [_phaseAllRedInputTextField release];
    [_addNewPhaseButton release];
//    [_timerGroupID release];
//    [_signalID release];
    [_ring1LabelList release];
    [_ring2LabelList release];
    [_labelList release];
    [_textFieldList release];
    [_removePhaseButton release];
    [_savePhaseEditButton release];
    [_signalOffsetTextField release];
    [_timingPattern release];
    [_subSystem release];
    [_agency release];
    [_signal release];
    [_beginOrEndArray release];
//    [_picker release];
    [_offsetPhaseLabel release];
    [_phasePicker release];
    [_phaseOffSetText release];
    [_selectedPhase release];
    [_mapButton release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.beginOrEndArray=[[[NSArray alloc] initWithObjects:@"Green Begin",@"Green End", nil] autorelease];
    
    self.view.backgroundColor = [UIColor clearColor];
    //    UIImageView *backgroundView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]] autorelease];
    
    //    [self.navigationController.view addSubview:backgroundView];
    //    [self.navigationController.view sendSubviewToBack:backgroundView];
    self.view.opaque = NO;
//    self.tableView.backgroundView = nil;
    //    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
//    self.offsetPhaseLabel.tag=-1;
//    [self addLabelResponder:self.offsetPhaseLabel];
    
    [self.removePhaseButton setHidden:YES];
    [self.savePhaseEditButton setHidden:YES];
    [_signalNameTextField setKeyboardType:UIKeyboardTypeDefault];
    [_signalCycleLengthField setKeyboardType:UIKeyboardTypeDecimalPad];
    [_signalOffsetTextField setKeyboardType:UIKeyboardTypeDecimalPad];
    [_phaseNoInputTextField setKeyboardType:UIKeyboardTypeDecimalPad];
    [_phaseMovementInputTextField  setKeyboardType:UIKeyboardTypeDefault];
    [_phaseRingInputTextField setKeyboardType:UIKeyboardTypeDecimalPad];
    [_phaseGreenInputTextField setKeyboardType:UIKeyboardTypeDecimalPad];
    [_phaseYellowInputTextField setKeyboardType:UIKeyboardTypeDecimalPad];
    [_phaseAllRedInputTextField setKeyboardType:UIKeyboardTypeDecimalPad];
    
    if (!_textFieldList) {
        _textFieldList=[[NSMutableArray alloc] init];
        [_textFieldList addObject:_signalNameTextField];
        [_textFieldList addObject:_signalCycleLengthField];
        [_textFieldList addObject:_signalOffsetTextField];
        [_textFieldList addObject:_phaseNoInputTextField];
        [_textFieldList addObject:_phaseMovementInputTextField];
        [_textFieldList addObject:_phaseRingInputTextField];
        [_textFieldList addObject:_phaseGreenInputTextField];
        [_textFieldList addObject:_phaseYellowInputTextField];
        [_textFieldList addObject:_phaseAllRedInputTextField];
    }
    if (!_labelList) {
        _labelList=[[NSMutableArray alloc] init];
    }
    self.timingRing1GraphPositionX=TIMING_RING1_GRAPH_INITIAL_POSITION_X;
    self.timingRing2GraphPositionX=TIMING_RING2_GRAPH_INITIAL_POSITION_X;
    int timingGraphPositionY=TIMING_RING1_GRAPH_POSITION_Y;
    int timingGraphHeight=TIMING_RING1_GRAPH_HEIGHT;
    
    
    if (!_signal) {
        [[self navigationController] setNavigationBarHidden:NO];
        UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(saveSignal:)];
        self.navigationItem.rightBarButtonItem = item;
        self.signalOffsetTextField.text=@"0";
        [item release];
//        [self.editButtonItem setStyle:UIBarButtonSystemItemSave];
        return;
    }
    
    
    // Do any additional setup after loading the view from its nib.
    if (!_ring1LabelList) {
        _ring1LabelList=[[NSMutableArray alloc] init];
    }
    if (!_ring2LabelList) {
        _ring2LabelList=[[NSMutableArray alloc] init];
    }
    
    if (!_signalNameTextField) {
        _signalNameTextField=[[UITextField alloc] init];
    }
    [_signalNameTextField setText:self.signal.signalName];
    [_signalNameTextField setDelegate:self];
    if (!_signalCycleLengthField) {
        _signalCycleLengthField=[[UITextField alloc] init];
    }
    [_signalCycleLengthField setText:self.signal.cycleLength];
    [_signalCycleLengthField setDelegate:self];
    
    [_signalOffsetTextField setText:self.signal.offset];
    [_signalCycleLengthField setDelegate:self];
    
    NSArray *ring1PhaseList=self.signal.ring1.phaseList;
    NSArray *ring2PhaseList=self.signal.ring2.phaseList;
    
    int ring1BarrierTime=0;
    for (int i=0; i<ring1PhaseList.count; i++) {
        SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
        if ([phase.barrier intValue]==1) {
            int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
            int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
            int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
            ring1BarrierTime=ring1BarrierTime+greenPhaseLength+yellowPhaseLength+allRedPhaseLength;
        }
    }
    ring1BarrierTime=ring1BarrierTime+TIMING_RING1_GRAPH_INITIAL_POSITION_X;
    int ring2BarrierTime=0;
    for (int i=0; i<ring2PhaseList.count; i++) {
        SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
        if ([phase.barrier intValue]==1) {
            int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
            int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
            int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
            ring2BarrierTime=ring2BarrierTime+greenPhaseLength+yellowPhaseLength+allRedPhaseLength;
        }
    }
    ring2BarrierTime=ring2BarrierTime+TIMING_RING2_GRAPH_INITIAL_POSITION_X;
    double barrierTime=0;
    if (ring1BarrierTime>=ring2BarrierTime) {
        barrierTime=ring1BarrierTime;
    }else{
        barrierTime=ring2BarrierTime;
    }
    int barrierPositionX=barrierTime;
    
    for (int i=0; i<ring1PhaseList.count; i++) {
        SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
        if ([phase.barrier intValue]==2 && self.timingRing1GraphPositionX<barrierPositionX) {
            self.timingRing1GraphPositionX=barrierPositionX;
        }
        int greenPhaseLength=300*[phase.greenTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
        int yellowPhaseLength=300*[phase.yellowTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
        int allRedPhaseLength=300*[phase.allRedTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
        UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
        greenLabel.tag=100+i;
        greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
        greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
        greenLabel.textAlignment = UITextAlignmentCenter;
        greenLabel.backgroundColor = [UIColor greenColor];
        greenLabel.textColor=[UIColor darkGrayColor];  
        [self addLabelResponder:greenLabel];
        [self.labelList addObject:greenLabel];
         [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+greenPhaseLength;
        
         UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
        yellowLabel.backgroundColor = [UIColor yellowColor];      
        
        [self.labelList addObject:yellowLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+yellowPhaseLength;
        
        UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
        allRedLabel.backgroundColor = [UIColor redColor];      
        
        [self.labelList addObject:allRedLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+allRedPhaseLength;
    }
    {
        UILabel *barrierLabel = [[[UILabel alloc] initWithFrame:CGRectMake(barrierPositionX,timingGraphPositionY,5,timingGraphHeight+10)] autorelease];
        barrierLabel.backgroundColor = [UIColor blackColor];
            barrierLabel.tag=300;
        [self.labelList addObject:barrierLabel];
        [self.view addSubview:barrierLabel];
    }
    
    
    timingGraphPositionY=TIMING_RING2_GRAPH_POSITION_Y;
    timingGraphHeight=TIMING_RING2_GRAPH_HEIGHT;
    for (int i=0; i<ring2PhaseList.count; i++) {
        SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
        if ([phase.barrier intValue]==2 && self.timingRing2GraphPositionX<barrierPositionX) {
            self.timingRing2GraphPositionX=barrierPositionX;
        }
        int greenPhaseLength=300*[phase.greenTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
        int yellowPhaseLength=300*[phase.yellowTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
        int allRedPhaseLength=300*[phase.allRedTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
        UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
            greenLabel.tag=200+i;
            greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
            greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
            greenLabel.textAlignment = UITextAlignmentCenter;
            greenLabel.backgroundColor = [UIColor greenColor];
            greenLabel.textColor=[UIColor darkGrayColor];  
        [self addLabelResponder:greenLabel];
        [self.labelList addObject:greenLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        
//        [self.labelList addObject:greenLabel];
//        UILabel * tempLabel=[self.labelList objectAtIndex:self.labelList.count-1];
//        [[self.labelList objectAtIndex:self.labelList.count-1] removeFromSuperview];
            
        self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+greenPhaseLength;
        
         UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
            yellowLabel.backgroundColor = [UIColor yellowColor];      
            
        [self.labelList addObject:yellowLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+yellowPhaseLength;
        
        UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
        allRedLabel.backgroundColor = [UIColor redColor];      
        
        [self.labelList addObject:allRedLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+allRedPhaseLength;
    }
    {
        UILabel *barrierLabel = [[[UILabel alloc] initWithFrame:CGRectMake(barrierPositionX,timingGraphPositionY,5,timingGraphHeight)] autorelease];
        barrierLabel.backgroundColor = [UIColor blackColor];
            barrierLabel.tag=300;
        [self.labelList addObject:barrierLabel];
        [self.view addSubview:barrierLabel];
    }
    
    
    [self.phasePicker setHidden:YES];
    self.phaseOffSetText.enabled=NO;
    
    if (self.signal.offsetPhase==nil||[self.signal.offsetPhase isEqualToString:@""]) {
        self.phaseOffSetText.text=@"";
    }else {
        self.phaseOffSetText.text=[NSString stringWithFormat:@"Phase %@  %@",self.signal.offsetPhase,self.signal.offsetBorE];
    }
    
    
    [self.navigationController setToolbarHidden:NO];
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
    UIBarButtonItem *space=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
    CustomizedBarButtonItem *signalCountingButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"CountingSignal.png"] target:self action:@selector(goToSignalCounting:)] autorelease];
    self.toolbarItems = [ NSArray arrayWithObjects: homeButtonItem,space,signalCountingButton,nil ];
    
}

- (void)viewDidUnload
{

    [self setRemovePhaseButton:nil];
    [self setSavePhaseEditButton:nil];
    [self setSignalOffsetTextField:nil];
    [self setOffsetPhaseLabel:nil];
    [self setPhasePicker:nil];
    [self setPhaseOffSetText:nil];
    [self setMapButton:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.signalNameTextField=nil;
    self.signalCycleLengthField=nil;
    self.cycleTimerLabel=nil;
    self.ring1TimerLabel=nil;
    self.ring2TimerLabel=nil;
    self.phaseNoInputTextField=nil;
    self.phaseMovementInputTextField=nil;
    self.phaseRingInputTextField=nil;
    self.phaseGreenInputTextField=nil;
    self.phaseYellowInputTextField=nil;
    self.phaseAllRedInputTextField=nil;
    self.addNewPhaseButton=nil;
//    self.timerGroupID=nil;
//    self.signalID=nil;
    self.ring1LabelList=nil;
    self.ring2TimerLabel=nil;
    self.labelList=nil;
    self.textFieldList=nil;
    self.timingPattern=nil;
    self.subSystem=nil;
    self.agency=nil;
    self.signal=nil;
    self.beginOrEndArray=nil;
    self.selectedPhase=nil;
//    self.picker=nil;
    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void) viewWillAppear:(BOOL)animated
{
//    [self.navigationController setToolbarHidden:YES];
    [super viewWillAppear:animated];
    self.signalCycleLengthField.text=self.signal.cycleLength;
    self.signalOffsetTextField.text=self.signal.offset;
    [self updateLabels];
}

- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.timer invalidate];
//    [self.timer invalidate];
//    if (!self.signal && ![self.signalNameTextField.text isEqualToString:@""]) {
//        _signal=[[Signal alloc] init];
//        [_signal setSignalID:self.signalID];
//        [_signal setSignalName:self.signalNameTextField.text];
//        [_signal setOffset:self.signalOffsetTextField.text];
//        [XMLParser updateSignal:self.timerGroupID signal:_signal];
//    } 
//    if (!self.signal && ![self.signalCycleLengthField.text isEqualToString:@""]) {
//        _signal=[[Signal alloc] init];
//        [_signal setSignalID:self.signalID];
//        [_signal setCycleLength:self.signalCycleLengthField.text];
//        [_signal setOffset:self.signalOffsetTextField.text];
//        [XMLParser updateSignal:self.timerGroupID signal:_signal];
//    } 
    if (self.signal)
    {
        [self.signal setSignalName:self.signalNameTextField.text];
        Intersection *intersection=[XMLParser getIntersection:self.signal.signalID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
        intersection.intersectionName=self.signalNameTextField.text;
        [XMLParser updateIntersection:intersection agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
        [self.signal setCycleLength:self.signalCycleLengthField.text];
        [self.signal setOffset:self.signalOffsetTextField.text];
        [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
    }
    NSArray *ring1PhaseList=self.signal.ring1.phaseList;
    double ring1SplitsSum=0;
    for (SignalPhase *phase in ring1PhaseList) {
        ring1SplitsSum=ring1SplitsSum+[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue];
    }
    
    
    NSArray *ring2PhaseList=self.signal.ring2.phaseList;
    double ring2SplitsSum=0;
    for (SignalPhase *phase in ring2PhaseList) {
        ring2SplitsSum=ring2SplitsSum+[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue];
    }
    if (ring1SplitsSum>0 && ring1SplitsSum!=[self.signal.cycleLength doubleValue]&&ring2SplitsSum>0 && ring2SplitsSum!=[self.signal.cycleLength doubleValue]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" 
                                                        message:[NSString stringWithFormat:@"%@\nRing1 & Ring2,\nThe splits do not add up to the cycle length!",self.signal.signalName] 
                                                       delegate:self 
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
    if (ring1SplitsSum>0 && ring1SplitsSum!=[self.signal.cycleLength doubleValue]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" 
                                                        message:[NSString stringWithFormat:@"%@\nRing1,\nThe splits do not add up to the cycle length!",self.signal.signalName] 
                                                       delegate:self 
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
    if (ring2SplitsSum>0 && ring2SplitsSum!=[self.signal.cycleLength doubleValue]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" 
                                                        message:[NSString stringWithFormat:@"%@\nRing2,\nThe splits do not add up to the cycle length!",self.signal.signalName] 
                                                       delegate:self 
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
}
- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (!self.signal) {
        return;
    }
    if (self.signal.cycleLength==0) {
        return;
    }
//    self.timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
//    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
#pragma mark - Text Field delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect textFieldRect =
    [self.view.window convertRect:textField.bounds fromView:textField];
    CGRect viewRect =
    [self.view.window convertRect:self.view.bounds fromView:self.view];
    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator = midline - viewRect.origin.y- MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    CGFloat denominator =(MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)
    * viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;
    if (heightFraction < 0.0)
    {
        heightFraction = 0.0;
    }
    else if (heightFraction > 1.0)
    {
        heightFraction = 1.0;
    }
    UIInterfaceOrientation orientation =
    [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIInterfaceOrientationPortrait ||
        orientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
    }
    else
    {
        animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
    }
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (self.signal)
    {
        [self.signal setSignalName:self.signalNameTextField.text];
        [self.signal setCycleLength:self.signalCycleLengthField.text];
        [self.signal setOffset:self.signalOffsetTextField.text];
        [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
        [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
    }
//    switch (textField.tag) {
//        case SignalCycleLengthField:
//        {
////            if (!self.signal && ![self.signalNameTextField.text isEqualToString:@""]) {
////                _signal=[[Signal alloc] init];
////                [_signal setSignalID:self.signalID];
////                [_signal setSignalName:self.signalNameTextField.text];
////                [_signal setOffset:self.signalOffsetTextField.text];
////                [XMLParser updateSignal:self.timerGroupID signal:_signal];
////            } 
////            if (!self.signal && ![self.signalCycleLengthField.text isEqualToString:@""]) {
////                _signal=[[Signal alloc] init];
////                [_signal setSignalID:self.signalID];
////                [_signal setCycleLength:self.signalCycleLengthField.text];
////                [_signal setOffset:self.signalOffsetTextField.text];
////                [XMLParser updateSignal:self.timerGroupID signal:_signal];
////            } 
//            if (self.signal)
//            {
//                [self.signal setSignalName:self.signalNameTextField.text];
//                [self.signal setCycleLength:self.signalCycleLengthField.text];
//                [self.signal setOffset:self.signalOffsetTextField.text];
//                [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
//            }
//        }
//        case SignalOffsetField:
//        {
//            if (self.signal)
//            {
//                [self.signal setOffset:self.signalOffsetTextField.text];
//                
//                [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
//            }
//        }
//            break;
//            
//        default:
//            break;
//    }
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
}

- (IBAction)clickAddNewPhaseButton:(id)sender {
//    if (!self.signal && ![self.signalNameTextField.text isEqualToString:@""]) {
//        _signal=[[Signal alloc] init];
//        [_signal setSignalID:self.signalID];
//        [_signal setSignalName:self.signalNameTextField.text];
//        [_signal setOffset:self.signalOffsetTextField.text];
//        [XMLParser updateSignal:self.timerGroupID signal:_signal];
//    } 
//    if (!self.signal && ![self.signalCycleLengthField.text isEqualToString:@""]) {
//        _signal=[[Signal alloc] init];
//        [_signal setSignalID:self.signalID];
//        [_signal setCycleLength:self.signalCycleLengthField.text];
//        [_signal setOffset:self.signalOffsetTextField.text];
//        [XMLParser updateSignal:self.timerGroupID signal:_signal];
//    } 
    if (self.signal)
    {
        [self.signal setSignalName:self.signalNameTextField.text];
        [self.signal setCycleLength:self.signalCycleLengthField.text];
        [self.signal setOffset:self.signalOffsetTextField.text];
        [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
    }
    if ([self.signalCycleLengthField.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" 
                                                        message:@"Please input the cycle length first!" 
                                                       delegate:self 
                                              cancelButtonTitle:@"YES"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }else {
        if ([self.phaseNoInputTextField.text isEqualToString:@""]||[self.phaseMovementInputTextField.text isEqualToString:@""]||[self.phaseRingInputTextField.text isEqualToString:@""]||[self.phaseGreenInputTextField.text isEqualToString:@""]||[self.phaseYellowInputTextField.text isEqualToString:@""]||[self.phaseAllRedInputTextField.text isEqualToString:@""]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" 
                                                            message:@"Please fill all the phase information!" 
                                                           delegate:self 
                                                  cancelButtonTitle:@"YES"
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
        }else {
            
            SignalPhase *phase=[[[SignalPhase alloc] init] autorelease];
            
            [phase setPhaseID:self.phaseNoInputTextField.text];
            [phase setPhaseMovement:self.phaseMovementInputTextField.text];
            double greenTime=[self.phaseGreenInputTextField.text doubleValue]-[self.phaseYellowInputTextField.text doubleValue]-[self.phaseAllRedInputTextField.text doubleValue];
                                                                                                    
            [phase setGreenTime:[NSString stringWithFormat:@"%.1f",greenTime]];
            [phase setYellowTime:self.phaseYellowInputTextField.text];
            [phase setAllRedTime:self.phaseAllRedInputTextField.text];
            
            
            [XMLParser createPhase:phase agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID signalID:self.signal.signalID signalRingID:self.phaseRingInputTextField.text];
            self.signal=[XMLParser getSignal:self.signal.signalID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
            [self.phaseNoInputTextField setText:@""];
//            [phase setPhaseMovement:self.phaseMovementInputTextField.text];
            [self.phaseMovementInputTextField setText:@""];
//            [phase setGreenTime:self.phaseGreenInputTextField.text];
            [self.phaseGreenInputTextField setText:@""];
//            [phase setYellowTime:self.phaseYellowInputTextField.text];
            [self.phaseYellowInputTextField setText:@""];
//            [phase setAllRedTime:self.phaseAllRedInputTextField.text];
            [self.phaseAllRedInputTextField setText:@""];
//           if ([self.phaseRingInputTextField.text isEqualToString:@"1"]) {
//               [self.signal.ring1.phaseList addObject:phase];
//           }else {
//               [self.signal.ring2.phaseList addObject:phase];
//           }
//            [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID]; 
//            for (int i=0; i<self.signal.ring2.phaseList.count; i++) {
//                NSLog(@"%@",[[self.signal.ring2.phaseList objectAtIndex:i] phaseID]);
//            }
            
            
            if ([self.phaseRingInputTextField.text isEqualToString:@"1"]) {
                int timingGraphPositionY=TIMING_RING1_GRAPH_POSITION_Y;
                int timingGraphHeight=TIMING_RING1_GRAPH_HEIGHT;
                int greenPhaseLength=300*[phase.greenTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
                int yellowPhaseLength=300*[phase.yellowTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
                int allRedPhaseLength=300*[phase.allRedTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
                UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
                greenLabel.tag=100+self.signal.ring1.phaseList.count-1;
                greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
                greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
                greenLabel.textAlignment = UITextAlignmentCenter;
                greenLabel.backgroundColor = [UIColor greenColor];
                greenLabel.textColor=[UIColor darkGrayColor];   
                [self addLabelResponder:greenLabel];
                [self.labelList addObject:greenLabel];
                [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
               
                self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+greenPhaseLength;
                
                UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
                yellowLabel.backgroundColor = [UIColor yellowColor];      
                
                [self.labelList addObject:yellowLabel];
                [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
                self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+yellowPhaseLength;
                
                UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
                allRedLabel.backgroundColor = [UIColor redColor];      
             
                [self.labelList addObject:allRedLabel];
                [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
                self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+allRedPhaseLength;
            }else {
                int timingGraphPositionY=TIMING_RING2_GRAPH_POSITION_Y;
                int timingGraphHeight=TIMING_RING2_GRAPH_HEIGHT;
                int greenPhaseLength=300*[phase.greenTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
                int yellowPhaseLength=300*[phase.yellowTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
                int allRedPhaseLength=300*[phase.allRedTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
                UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
                greenLabel.tag=200+self.signal.ring2.phaseList.count-1;
                greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
                greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
                greenLabel.textAlignment = UITextAlignmentCenter;
                greenLabel.backgroundColor = [UIColor greenColor];
                greenLabel.textColor=[UIColor darkGrayColor];      
                [self addLabelResponder:greenLabel];
                [self.labelList addObject:greenLabel];
                [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
               
                self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+greenPhaseLength;
                
                UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
                yellowLabel.backgroundColor = [UIColor yellowColor];      
                
                [self.labelList addObject:yellowLabel];
                [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
                self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+yellowPhaseLength;
                
                UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
                allRedLabel.backgroundColor = [UIColor redColor];      
                
                [self.labelList addObject:allRedLabel];
                [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
                self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+allRedPhaseLength;
            }
            
            [self.phaseRingInputTextField setText:@""];
            
            
            
        }
    }
}
- (id) initWithNibNameTimerGroupIDAndSignalID:(NSString *)nibName timerGroupID:(NSString *)timerGroupID signalID:(NSString *)signalID bundle:(NSBundle *)nibBundle
{
    self=[super initWithNibName:nibName bundle:nibBundle];
    if(self)
    {
//        self.timerGroupID=timerGroupID;
//        self.signalID=signalID;
    }
    return self;
}
-(IBAction)textFieldReturn:(id)sender
{
    [sender resignFirstResponder];
}

-(IBAction)backgroundTouched:(id)sender
{
    for (int i=0; i<self.textFieldList.count; i++) {
        [[self.textFieldList objectAtIndex:i] resignFirstResponder];
    }
    self.navigationItem.rightBarButtonItem = nil;
    [self.phasePicker setHidden:YES];
    self.title=@"Edit Signal";
    if (self.signal.offsetPhase==nil||[self.signal.offsetPhase isEqualToString:@""]) {
        self.phaseOffSetText.text=@"";
    }else {
        self.phaseOffSetText.text=[NSString stringWithFormat:@"Phase %@  %@",self.signal.offsetPhase,self.signal.offsetBorE];
    }
}

- (IBAction)clickOffsetPhaseButton:(id)sender {
    UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(selectOffSetPhase:)];
    self.navigationItem.rightBarButtonItem = item;
    [item release];
    [self.editButtonItem setStyle:UIBarButtonItemStyleDone];
    [self.phasePicker reloadAllComponents];
    [self.phasePicker setHidden:NO];
    [self.view bringSubviewToFront:self.phasePicker];
//    [self.phasePicker 
    self.title=@"Select Offset Phase";
    return; 
        
    
}


- (void) updateTimer:(id) sender {
    
    
   
    int cycleTimer=[TrafficSignalTimer calculateCycleTimer:[self.signal.cycleLength doubleValue] offSet:[self.signal.offset doubleValue] syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset doubleValue]];
    self.cycleTimerLabel.text=[NSString stringWithFormat:@"%.1f", cycleTimer];

    int cycleTimerTemp=cycleTimer;
    if (self.signal.ring1.phaseList==nil || self.signal.ring1.phaseList.count==0) {
        self.ring1TimerLabel.text=@"";
    }
    for (int i=0; i<self.signal.ring1.phaseList.count; i++) {
        SignalPhase *phase=[self.signal.ring1.phaseList objectAtIndex:i];
        if (cycleTimer<[phase.greenTime doubleValue]) {
            self.ring1TimerLabel.text=[[[[[[NSString stringWithString:@"Phase "] stringByAppendingString:phase.phaseID] stringByAppendingString:@" Green "] stringByAppendingString:@" - "] stringByAppendingFormat:@"%.1f/", cycleTimer] stringByAppendingFormat:@"%.1f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])];
            break;
        }
        if (cycleTimer<[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]) {
            self.ring1TimerLabel.text=[[[[[[NSString stringWithString:@"Phase "] stringByAppendingString:phase.phaseID] stringByAppendingString:@" Yellow "] stringByAppendingString:@" - "] stringByAppendingFormat:@"%.1f/", cycleTimer] stringByAppendingFormat:@"%.1f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])];
            break;
        }
        if (cycleTimer<[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]) {
            self.ring1TimerLabel.text=[[[[[[NSString stringWithString:@"Phase "] stringByAppendingString:phase.phaseID] stringByAppendingString:@" AllRed "] stringByAppendingString:@" - "] stringByAppendingFormat:@"%.1f/", cycleTimer] stringByAppendingFormat:@"%.1f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])];
            break;
        }
        cycleTimer=cycleTimer-([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]);
        self.ring1TimerLabel.text=@"";
    }
    
    cycleTimer=cycleTimerTemp;
    if (self.signal.ring2.phaseList==nil || self.signal.ring2.phaseList.count==0) {
        self.ring2TimerLabel.text=@"";
    }
    for (int i=0; i<self.signal.ring2.phaseList.count; i++) {
        SignalPhase *phase=[self.signal.ring2.phaseList objectAtIndex:i];
        if (cycleTimer<[phase.greenTime doubleValue]) {
            self.ring2TimerLabel.text=[[[[[[NSString stringWithString:@"Phase "] stringByAppendingString:phase.phaseID] stringByAppendingString:@" Green "] stringByAppendingString:@" - "] stringByAppendingFormat:@"%.1f/", cycleTimer] stringByAppendingFormat:@"%.1f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])];
            break;
        }
        if (cycleTimer<[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]) {
            self.ring2TimerLabel.text=[[[[[[NSString stringWithString:@"Phase "] stringByAppendingString:phase.phaseID] stringByAppendingString:@" Yellow "] stringByAppendingString:@" - "] stringByAppendingFormat:@"%.1f/", cycleTimer] stringByAppendingFormat:@"%.1f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])];
            break;
        }
        if (cycleTimer<[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]) {
            self.ring2TimerLabel.text=[[[[[[NSString stringWithString:@"Phase "] stringByAppendingString:phase.phaseID] stringByAppendingString:@" AllRed "] stringByAppendingString:@" - "] stringByAppendingFormat:@"%.1f/", cycleTimer] stringByAppendingFormat:@"%.1f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])];
            break;
        }
        cycleTimer=cycleTimer-([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]);
        
    }
    
     
    
}
- (void) addLabelResponder:(UILabel *) label 
{
    [label setUserInteractionEnabled:YES];
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickLabel:)];
    [tapGestureRecognizer setNumberOfTapsRequired:1];
    [label addGestureRecognizer:tapGestureRecognizer];
    [tapGestureRecognizer release];
    
    UIPanGestureRecognizer *dragGesture = [[[UIPanGestureRecognizer alloc] 
                                        initWithTarget:self 
                                        action:@selector(labelDragged:)] autorelease];

	[label addGestureRecognizer:dragGesture];
}

- (IBAction)clickLabel:(id)sender
{
    UITapGestureRecognizer *tapGesture=(UITapGestureRecognizer *)sender;
    UIView *label=tapGesture.view;
//    UILabel *label=(UILabel *)sender;
    int labelTag=label.tag;
    
    if (labelTag<200) {
        labelTag=labelTag-100;
        SignalPhase *phase=[self.signal.ring1.phaseList objectAtIndex:labelTag];
        self.selectedPhase=phase;
        self.phaseNoInputTextField.text=phase.phaseID;
        self.phaseMovementInputTextField.text=phase.phaseMovement;
        self.phaseRingInputTextField.text=@"1";
        
        double phaseTime=[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue];
        self.phaseGreenInputTextField.text=[NSString stringWithFormat:@"%.1f",phaseTime];
        self.phaseYellowInputTextField.text=phase.yellowTime;
        self.phaseAllRedInputTextField.text=phase.allRedTime;
    }else {
        labelTag=labelTag-200;
        SignalPhase *phase=[self.signal.ring2.phaseList objectAtIndex:labelTag];
        self.selectedPhase=phase;
        self.phaseNoInputTextField.text=phase.phaseID;
        self.phaseMovementInputTextField.text=phase.phaseMovement;
        self.phaseRingInputTextField.text=@"2";
        
        double phaseTime=[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue];
        self.phaseGreenInputTextField.text=[NSString stringWithFormat:@"%.1f",phaseTime];
        self.phaseYellowInputTextField.text=phase.yellowTime;
        self.phaseAllRedInputTextField.text=phase.allRedTime;
    }
    
    [self.removePhaseButton setHidden:NO];
    [self.savePhaseEditButton setHidden:NO];
    [self.addNewPhaseButton setHidden:YES];
    [self.view setNeedsDisplay];
    
    
    
    
    

}
- (void)labelDragged:(UIPanGestureRecognizer *)gesture
{
	UILabel *label = (UILabel *)gesture.view;
    if (label.tag<100) {
        return;
    }
	CGPoint translation = [gesture translationInView:label];
    
        
	// move label
	label.center = CGPointMake(label.center.x + translation.x, 
                               label.center.y);

    
    int index=[self.labelList indexOfObject:label];
    UILabel *yellowLabel=[self.labelList objectAtIndex:index+1];
    UILabel *redLabel=[self.labelList objectAtIndex:index+2];                      
    yellowLabel.center = CGPointMake(yellowLabel.center.x + translation.x, 
                               yellowLabel.center.y);
    redLabel.center = CGPointMake(redLabel.center.x + translation.x, 
                               redLabel.center.y);
    
	// reset translation
	[gesture setTranslation:CGPointZero inView:label];
    
    for (int i=0; i<self.labelList.count; i++) {
        UILabel *otherLabel=[self.labelList objectAtIndex:i];
        if (label.tag==otherLabel.tag) {
            continue;
        }
        if (otherLabel.tag<300) {
            continue;
        }
        
        CGPoint destinationPoint=label.center;
        CGRect otherLabelRect=otherLabel.frame;
        BOOL inRect=CGRectContainsPoint(otherLabelRect,destinationPoint);
        if (inRect) {
            if (otherLabel.tag==300) {
                NSLog(@"\n otherLabel.tag=300");
            }
            int labelTag=label.tag;
            
            if (labelTag<200) {
                
                labelTag=labelTag-100;
                int otherLabelTag=otherLabel.tag;
                if (otherLabelTag==300) {
                    SignalPhase *labelPhase=[self.signal.ring1.phaseList objectAtIndex:labelTag];
                    int labelBarrier=[labelPhase.barrier intValue];
                    if (labelBarrier==1) {
                        labelPhase.barrier=[NSString stringWithFormat:@"%d",2];
                    }else
                    {
                        labelPhase.barrier=[NSString stringWithFormat:@"%d",1];
                    }
                    
                }
                
            }else {
                labelTag=labelTag-200;
                int otherLabelTag=otherLabel.tag;
                if (otherLabelTag==300) {
                    SignalPhase *labelPhase=[self.signal.ring2.phaseList objectAtIndex:labelTag];
                    int labelBarrier=[labelPhase.barrier intValue];
                    if (labelBarrier==1) {
                        labelPhase.barrier=[NSString stringWithFormat:@"%d",2];
                    }else
                    {
                        labelPhase.barrier=[NSString stringWithFormat:@"%d",1];
                    }
                    
                }
            }
            [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
            [label removeGestureRecognizer:gesture];
            [self updateLabels];
            return;
            
            
        }
        
        
    }
    
    for (int i=0; i<self.labelList.count; i++) {
        UILabel *otherLabel=[self.labelList objectAtIndex:i];
        if (label.tag==otherLabel.tag) {
            continue;
        }
        if (otherLabel.tag<100) {
            continue;
        }
        
        CGPoint destinationPoint=label.center;
        CGRect otherLabelRect=otherLabel.frame;
        BOOL inRect=CGRectContainsPoint(otherLabelRect,destinationPoint);
        if (inRect) {
            if (otherLabel.tag==300) {
                NSLog(@"\n otherLabel.tag=300");
            }
            int labelTag=label.tag;
            
            if (labelTag<200) {
                
                labelTag=labelTag-100;
                int otherLabelTag=otherLabel.tag;
                if (otherLabelTag==300) {
                    return;
                    
                }else
                {
                    if (otherLabelTag<200) {
                        otherLabelTag=otherLabelTag-100;
                    }else {
                        otherLabelTag=otherLabelTag-200;
                    }
                    [self.signal.ring1.phaseList exchangeObjectAtIndex:labelTag withObjectAtIndex:otherLabelTag];
                }
                
            }else {
                labelTag=labelTag-200;
                int otherLabelTag=otherLabel.tag;
                if (otherLabelTag==300) {
                    return;
                    
                }else
                {
                    if (otherLabelTag<200) {
                        otherLabelTag=otherLabelTag-100;
                    }else {
                        otherLabelTag=otherLabelTag-200;
                    }
                    [self.signal.ring2.phaseList exchangeObjectAtIndex:labelTag withObjectAtIndex:otherLabelTag];
                }
            }
            [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
            [label removeGestureRecognizer:gesture];
            [self updateLabels];
            break;
            
            
        }
        
        
    }
    
    return;

}

- (IBAction)clickRemovePhaseButton:(id)sender
{
    [self.removePhaseButton setHidden:YES];
    [self.savePhaseEditButton setHidden:YES];
    [self.addNewPhaseButton setHidden:NO];
    
    [XMLParser removePhase:self.phaseNoInputTextField.text agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID signalID:self.signal.signalID signalRingID:self.phaseRingInputTextField.text];
    self.signal=[XMLParser getSignal:self.signal.signalID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
//    [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
//    [XMLParser removePhaseByTimerGroupIDSignalIDAndPhaseID:self.timerGroupID signalID:self.signalID ringID:self.phaseRingInputTextField.text phaseID:self.phaseNoInputTextField.text];
    
//    self.signal=[XMLParser getSignalByTimerGroupIDAndSignalID:self.timerGroupID signalID:self.signalID];
    self.phaseNoInputTextField.text=@"";
    self.phaseMovementInputTextField.text=@"";
    self.phaseRingInputTextField.text=@"";
    self.phaseGreenInputTextField.text=@"";
    self.phaseYellowInputTextField.text=@"";
    self.phaseAllRedInputTextField.text=@"";
//    [self.labelList addObject:greenLabel];
    while(self.labelList.count>0) {
        UILabel *label=[self.labelList objectAtIndex:0];
        [label removeFromSuperview];
        [self.labelList removeObjectAtIndex:0];
    }
    {
        NSArray *ring1PhaseList=self.signal.ring1.phaseList;
        NSArray *ring2PhaseList=self.signal.ring2.phaseList;
        
        int ring1BarrierTime=0;
        for (int i=0; i<ring1PhaseList.count; i++) {
            SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
            if ([phase.barrier intValue]==1) {
                int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
                int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
                int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
                ring1BarrierTime=ring1BarrierTime+greenPhaseLength+yellowPhaseLength+allRedPhaseLength;
            }
        }
        ring1BarrierTime=ring1BarrierTime+TIMING_RING1_GRAPH_INITIAL_POSITION_X;
        int ring2BarrierTime=0;
        for (int i=0; i<ring2PhaseList.count; i++) {
            SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
            if ([phase.barrier intValue]==1) {
                int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
                int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
                int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
                ring2BarrierTime=ring2BarrierTime+greenPhaseLength+yellowPhaseLength+allRedPhaseLength;
            }
        }
        ring2BarrierTime=ring2BarrierTime+TIMING_RING2_GRAPH_INITIAL_POSITION_X;
        double barrierTime=0;
        if (ring1BarrierTime>=ring2BarrierTime) {
            barrierTime=ring1BarrierTime;
        }else{
            barrierTime=ring2BarrierTime;
        }
        int barrierPositionX=barrierTime;
        
        self.timingRing1GraphPositionX=TIMING_RING1_GRAPH_INITIAL_POSITION_X;
        int timingGraphPositionY=TIMING_RING1_GRAPH_POSITION_Y;
        int timingGraphHeight=TIMING_RING1_GRAPH_HEIGHT;
        for (int i=0; i<ring1PhaseList.count; i++) {
            SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
            if ([phase.barrier intValue]==2 && self.timingRing1GraphPositionX<barrierPositionX) {
                self.timingRing1GraphPositionX=barrierPositionX;
            }
            int greenPhaseLength=300*[phase.greenTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            int yellowPhaseLength=300*[phase.yellowTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            int allRedPhaseLength=300*[phase.allRedTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
            greenLabel.tag=100+i;
            greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
            greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
            greenLabel.textAlignment = UITextAlignmentCenter;
            greenLabel.backgroundColor = [UIColor greenColor];
            greenLabel.textColor=[UIColor darkGrayColor];  
            [self addLabelResponder:greenLabel];
            [self.labelList addObject:greenLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+greenPhaseLength;
            
            UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
            yellowLabel.backgroundColor = [UIColor yellowColor];      
            
            [self.labelList addObject:yellowLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+yellowPhaseLength;
            
            UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
            allRedLabel.backgroundColor = [UIColor redColor];      
            
            [self.labelList addObject:allRedLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+allRedPhaseLength;
        }
        {
            UILabel *barrierLabel = [[[UILabel alloc] initWithFrame:CGRectMake(barrierPositionX,timingGraphPositionY,5,timingGraphHeight+10)] autorelease];
            barrierLabel.backgroundColor = [UIColor blackColor];
            barrierLabel.tag=300;
            [self.labelList addObject:barrierLabel];
            [self.view addSubview:barrierLabel];
        }
        
        self.timingRing2GraphPositionX=TIMING_RING2_GRAPH_INITIAL_POSITION_X;
        timingGraphPositionY=TIMING_RING2_GRAPH_POSITION_Y;
        timingGraphHeight=TIMING_RING2_GRAPH_HEIGHT;
        for (int i=0; i<ring2PhaseList.count; i++) {
            SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
            if ([phase.barrier intValue]==2 && self.timingRing2GraphPositionX<barrierPositionX) {
                self.timingRing2GraphPositionX=barrierPositionX;
            }
            int greenPhaseLength=300*[phase.greenTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            int yellowPhaseLength=300*[phase.yellowTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            int allRedPhaseLength=300*[phase.allRedTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
            greenLabel.tag=200+i;
            greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
            greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
            greenLabel.textAlignment = UITextAlignmentCenter;
            greenLabel.backgroundColor = [UIColor greenColor];
            greenLabel.textColor=[UIColor darkGrayColor];  
            [self addLabelResponder:greenLabel];
            [self.labelList addObject:greenLabel];
           [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+greenPhaseLength;
            
            UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
            yellowLabel.backgroundColor = [UIColor yellowColor];      
            
            [self.labelList addObject:yellowLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+yellowPhaseLength;
            
            UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
            allRedLabel.backgroundColor = [UIColor redColor];      
            
            [self.labelList addObject:allRedLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+allRedPhaseLength;
        }
        {
            UILabel *barrierLabel = [[[UILabel alloc] initWithFrame:CGRectMake(barrierPositionX,timingGraphPositionY,5,timingGraphHeight)] autorelease];
            barrierLabel.backgroundColor = [UIColor blackColor];
            barrierLabel.tag=300;
            [self.labelList addObject:barrierLabel];
            [self.view addSubview:barrierLabel];
        }

    }
    [self.view setNeedsDisplay];
}
- (IBAction)clickSaveEditPhaseButton:(id)sender
{
    [self.removePhaseButton setHidden:YES];
    [self.savePhaseEditButton setHidden:YES];
    [self.addNewPhaseButton setHidden:NO];
    
    

        
//        SignalPhase *phase=[[[SignalPhase alloc] init] autorelease];
    SignalPhase *phase=self.selectedPhase;
        
        [phase setPhaseID:self.phaseNoInputTextField.text];
        [phase setPhaseMovement:self.phaseMovementInputTextField.text];
    double greenTime=[self.phaseGreenInputTextField.text doubleValue]-[self.phaseYellowInputTextField.text doubleValue]-[self.phaseAllRedInputTextField.text doubleValue];

        [phase setGreenTime:[NSString stringWithFormat:@"%.1f",greenTime]];
        [phase setYellowTime:self.phaseYellowInputTextField.text];
        [phase setAllRedTime:self.phaseAllRedInputTextField.text];
        
    int ringNumber=0;
    
    if ([self.signal.ring1.phaseList containsObject:phase]) {
        ringNumber=1;
        if ([self.phaseRingInputTextField.text intValue]==ringNumber) {
            [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
        }else {
            [self.signal.ring2.phaseList insertObject:phase atIndex:self.signal.ring2.phaseList.count];
            [self.signal.ring1.phaseList removeObject:phase];
            [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
        }
    }else {
        ringNumber=2;
        if ([self.phaseRingInputTextField.text intValue]==ringNumber) {
            [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
        }else {
            [self.signal.ring1.phaseList insertObject:phase atIndex:self.signal.ring1.phaseList.count];
            [self.signal.ring2.phaseList removeObject:phase];
            [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
        }
    }
    self.selectedPhase=nil;
    
//    [XMLParser updatePhase:phase agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID signalID:self.signal.signalID signalRingID:self.phaseRingInputTextField.text];
//    self.signal=[XMLParser getSignal:self.signal.signalID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
//    [XMLParser updatePhase:self.timerGroupID signalID:self.signalID signalRingID:self.phaseRingInputTextField.text signaPhase:phase];
//    self.signal=[XMLParser getSignalByTimerGroupIDAndSignalID:self.timerGroupID signalID:self.signalID];
    self.phaseNoInputTextField.text=@"";
    self.phaseMovementInputTextField.text=@"";
    self.phaseRingInputTextField.text=@"";
    self.phaseGreenInputTextField.text=@"";
    self.phaseYellowInputTextField.text=@"";
    self.phaseAllRedInputTextField.text=@"";
    
    while(self.labelList.count>0) {
        UILabel *label=[self.labelList objectAtIndex:0];
        [label removeFromSuperview];
        [self.labelList removeObjectAtIndex:0];
    }
   
    
    {
        NSArray *ring1PhaseList=self.signal.ring1.phaseList;
        NSArray *ring2PhaseList=self.signal.ring2.phaseList;
        int ring1BarrierTime=0;
        for (int i=0; i<ring1PhaseList.count; i++) {
            SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
            if ([phase.barrier intValue]==1) {
                int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
                int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
                int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
                ring1BarrierTime=ring1BarrierTime+greenPhaseLength+yellowPhaseLength+allRedPhaseLength;
            }
        }
        ring1BarrierTime=ring1BarrierTime+TIMING_RING1_GRAPH_INITIAL_POSITION_X;
        int ring2BarrierTime=0;
        for (int i=0; i<ring2PhaseList.count; i++) {
            SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
            if ([phase.barrier intValue]==1) {
                int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
                int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
                int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
                ring2BarrierTime=ring2BarrierTime+greenPhaseLength+yellowPhaseLength+allRedPhaseLength;
            }
        }
        ring2BarrierTime=ring2BarrierTime+TIMING_RING2_GRAPH_INITIAL_POSITION_X;
        double barrierTime=0;
        if (ring1BarrierTime>=ring2BarrierTime) {
            barrierTime=ring1BarrierTime;
        }else{
            barrierTime=ring2BarrierTime;
        }
        int barrierPositionX=barrierTime;
        
        self.timingRing1GraphPositionX=TIMING_RING1_GRAPH_INITIAL_POSITION_X;
        int timingGraphPositionY=TIMING_RING1_GRAPH_POSITION_Y;
        int timingGraphHeight=TIMING_RING1_GRAPH_HEIGHT;
        for (int i=0; i<ring1PhaseList.count; i++) {
            if ([phase.barrier intValue]==2 && self.timingRing1GraphPositionX<barrierPositionX) {
                self.timingRing1GraphPositionX=barrierPositionX;
            }
            SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
            int greenPhaseLength=300*[phase.greenTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            int yellowPhaseLength=300*[phase.yellowTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            int allRedPhaseLength=300*[phase.allRedTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
            greenLabel.tag=100+i;
            greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
            greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
            greenLabel.textAlignment = UITextAlignmentCenter;
            greenLabel.backgroundColor = [UIColor greenColor];
            greenLabel.textColor=[UIColor darkGrayColor];  
            [self addLabelResponder:greenLabel];
            [self.labelList addObject:greenLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+greenPhaseLength;
            
            UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
            yellowLabel.backgroundColor = [UIColor yellowColor];      
           
            [self.labelList addObject:yellowLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+yellowPhaseLength;
            
            UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
            allRedLabel.backgroundColor = [UIColor redColor];      
           
            [self.labelList addObject:allRedLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+allRedPhaseLength;
        }
        {
            UILabel *barrierLabel = [[[UILabel alloc] initWithFrame:CGRectMake(barrierPositionX,timingGraphPositionY,5,timingGraphHeight+10)] autorelease];
            barrierLabel.backgroundColor = [UIColor blackColor];
            barrierLabel.tag=300;
            [self.labelList addObject:barrierLabel];
            [self.view addSubview:barrierLabel];
        }
        
        
        self.timingRing2GraphPositionX=TIMING_RING2_GRAPH_INITIAL_POSITION_X;
        timingGraphPositionY=TIMING_RING2_GRAPH_POSITION_Y;
        timingGraphHeight=TIMING_RING2_GRAPH_HEIGHT;
        for (int i=0; i<ring2PhaseList.count; i++) {
            SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
            if ([phase.barrier intValue]==2 && self.timingRing2GraphPositionX<barrierPositionX) {
                self.timingRing2GraphPositionX=barrierPositionX;
            }
            int greenPhaseLength=300*[phase.greenTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            int yellowPhaseLength=300*[phase.yellowTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            int allRedPhaseLength=300*[phase.allRedTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
            greenLabel.tag=200+i;
            greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
            greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
            greenLabel.textAlignment = UITextAlignmentCenter;
            greenLabel.backgroundColor = [UIColor greenColor];
            greenLabel.textColor=[UIColor darkGrayColor];  
            [self addLabelResponder:greenLabel];
            [self.labelList addObject:greenLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+greenPhaseLength;
            
            UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
            yellowLabel.backgroundColor = [UIColor yellowColor];      
           
            [self.labelList addObject:yellowLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+yellowPhaseLength;
            
            UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
            allRedLabel.backgroundColor = [UIColor redColor];      
            
            [self.labelList addObject:allRedLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+allRedPhaseLength;
        }
        {
            UILabel *barrierLabel = [[[UILabel alloc] initWithFrame:CGRectMake(barrierPositionX,timingGraphPositionY,5,timingGraphHeight)] autorelease];
            barrierLabel.backgroundColor = [UIColor blackColor];
            barrierLabel.tag=300;
            [self.labelList addObject:barrierLabel];
            [self.view addSubview:barrierLabel];
        }
        
    }
    [self.view setNeedsDisplay];
}

- (IBAction)saveSignal:(id)sender
{
//    if (!self.signal && ![self.signalNameTextField.text isEqualToString:@""]) {
//        _signal=[[Signal alloc] init];
//        [_signal setSignalID:self.signalID];
//        [_signal setSignalName:self.signalNameTextField.text];
//        [_signal setOffset:self.signalOffsetTextField.text];
//        [XMLParser updateSignal:self.timerGroupID signal:_signal];
//    } 
//    if (!self.signal && ![self.signalCycleLengthField.text isEqualToString:@""]) {
//        _signal=[[Signal alloc] init];
//        [_signal setSignalID:self.signalID];
//        [_signal setCycleLength:self.signalCycleLengthField.text];
//        [_signal setOffset:self.signalOffsetTextField.text];
//        [XMLParser updateSignal:self.timerGroupID signal:_signal];
//    } 
    if (self.signal)
    {
        [self.signal setSignalName:self.signalNameTextField.text];
        [self.signal setCycleLength:self.signalCycleLengthField.text];
        [self.signal setOffset:self.signalOffsetTextField.text];
        [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
    }
    if (self.signal) {
//        [self.timer invalidate];
        
        
        
        if (![self.signalCycleLengthField.text isEqualToString:@""]) {
            self.timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
            [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
            self.navigationItem.rightBarButtonItem =nil;
        }
       
    }else {
        [[self navigationController] popViewControllerAnimated:YES];
    }
}

- (id) initWithNibNameAndSignal:(NSString *)nibName agency:(Agency *)agency subSystem:(SubSystem *)subSystem timingPattern:(TimingPattern *)timingPattern signal:(Signal *)signal bundle:(NSBundle *)nibBundle
{
    self=[super initWithNibName:nibName bundle:nibBundle];
    self.agency=agency;
    self.subSystem=subSystem;
    self.timingPattern=timingPattern;
    self.signal=signal;
    return self;
}
             
- (void) updateLabels
{
//    for (int i=0; i<self.labelList.count; i++) {
//        UILabel *otherLabel=[self.labelList objectAtIndex:i];
//        if (otherLabel.tag<100) {
//            continue;
//        }
//        if (otherLabel.tag<200) {
//            //            labelTag=labelTag-100;
//            [self.ring1LabelList addObject:otherLabel];
//            
//        }else {
//            [self.ring2LabelList addObject:otherLabel];
//        }
//    }
    for (int i=0; i<self.labelList.count; i++) {
   
        UILabel *label=[self.labelList objectAtIndex:i];
        [label removeFromSuperview];
//        [self.labelList removeObjectAtIndex:0];
    }
    self.labelList=[[[NSMutableArray alloc]init] autorelease];
    
    {
        NSArray *ring1PhaseList=self.signal.ring1.phaseList;
        NSArray *ring2PhaseList=self.signal.ring2.phaseList;
        
        int ring1BarrierTime=0;
        for (int i=0; i<ring1PhaseList.count; i++) {
            SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
            if ([phase.barrier intValue]==1) {
                int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
                int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
                int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
                ring1BarrierTime=ring1BarrierTime+greenPhaseLength+yellowPhaseLength+allRedPhaseLength;
            }
        }
        ring1BarrierTime=ring1BarrierTime+TIMING_RING1_GRAPH_INITIAL_POSITION_X;
        int ring2BarrierTime=0;
        for (int i=0; i<ring2PhaseList.count; i++) {
            SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
            if ([phase.barrier intValue]==1) {
                int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
                int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
                int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
                ring2BarrierTime=ring2BarrierTime+greenPhaseLength+yellowPhaseLength+allRedPhaseLength;
            }
        }
        ring2BarrierTime=ring2BarrierTime+TIMING_RING2_GRAPH_INITIAL_POSITION_X;
        double barrierTime=0;
        if (ring1BarrierTime>=ring2BarrierTime) {
            barrierTime=ring1BarrierTime;
        }else{
            barrierTime=ring2BarrierTime;
        }
        int barrierPositionX=barrierTime;
        
        self.timingRing1GraphPositionX=TIMING_RING1_GRAPH_INITIAL_POSITION_X;
        int timingGraphPositionY=TIMING_RING1_GRAPH_POSITION_Y;
        int timingGraphHeight=TIMING_RING1_GRAPH_HEIGHT;
        for (int i=0; i<ring1PhaseList.count; i++) {
            SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
            if ([phase.barrier intValue]==2 && self.timingRing1GraphPositionX<barrierPositionX) {
                self.timingRing1GraphPositionX=barrierPositionX;
            }
            int greenPhaseLength=300*[phase.greenTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            int yellowPhaseLength=300*[phase.yellowTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            int allRedPhaseLength=300*[phase.allRedTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
//            UILabel *greenLabel = [self.labelList objectAtIndex:(i*3)];
            greenLabel.tag=100+i;
            greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
            greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
            greenLabel.textAlignment = UITextAlignmentCenter;
            greenLabel.backgroundColor = [UIColor greenColor];
            greenLabel.textColor=[UIColor darkGrayColor];  
            [self addLabelResponder:greenLabel];
            [self.labelList addObject:greenLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+greenPhaseLength;
            
            UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
            yellowLabel.backgroundColor = [UIColor yellowColor];      
            
            [self.labelList addObject:yellowLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+yellowPhaseLength;
            
            UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
            allRedLabel.backgroundColor = [UIColor redColor];      
            
            [self.labelList addObject:allRedLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+allRedPhaseLength;
        }
        {
            UILabel *barrierLabel = [[[UILabel alloc] initWithFrame:CGRectMake(barrierPositionX,timingGraphPositionY,5,timingGraphHeight+10)] autorelease];
            barrierLabel.backgroundColor = [UIColor blackColor];
            barrierLabel.tag=300;
            [self.labelList addObject:barrierLabel];
            [self.view addSubview:barrierLabel];
        }
        
        
        self.timingRing2GraphPositionX=TIMING_RING2_GRAPH_INITIAL_POSITION_X;
        timingGraphPositionY=TIMING_RING2_GRAPH_POSITION_Y;
        timingGraphHeight=TIMING_RING2_GRAPH_HEIGHT;
        for (int i=0; i<ring2PhaseList.count; i++) {
            SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
            if ([phase.barrier intValue]==2 && self.timingRing2GraphPositionX<barrierPositionX) {
                self.timingRing2GraphPositionX=barrierPositionX;
            }
            int greenPhaseLength=300*[phase.greenTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            int yellowPhaseLength=300*[phase.yellowTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            int allRedPhaseLength=300*[phase.allRedTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
            greenLabel.tag=200+i;
            greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
            greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
            greenLabel.textAlignment = UITextAlignmentCenter;
            greenLabel.backgroundColor = [UIColor greenColor];
            greenLabel.textColor=[UIColor darkGrayColor];  
            [self addLabelResponder:greenLabel];
            [self.labelList addObject:greenLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+greenPhaseLength;
            
            UILabel *yellowLabel =[[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
            yellowLabel.backgroundColor = [UIColor yellowColor];      
            
            [self.labelList addObject:yellowLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+yellowPhaseLength;
            
            UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
            allRedLabel.backgroundColor = [UIColor redColor];      
            
            [self.labelList addObject:allRedLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+allRedPhaseLength;
        }
        {
            UILabel *barrierLabel = [[[UILabel alloc] initWithFrame:CGRectMake(barrierPositionX,timingGraphPositionY,5,timingGraphHeight)] autorelease];
            barrierLabel.backgroundColor = [UIColor blackColor];
            barrierLabel.tag=300;
            [self.labelList addObject:barrierLabel];
            [self.view addSubview:barrierLabel];
        }
        
    }
    [self.view setNeedsDisplay];              
}

-(void) updateSignalLabels
{
    while(self.labelList.count>0) {
        UILabel *label=[self.labelList objectAtIndex:0];
        [label removeFromSuperview];
        [self.labelList removeObjectAtIndex:0];
    }
    
    
    {
        NSArray *ring1PhaseList=self.signal.ring1.phaseList;
        NSArray *ring2PhaseList=self.signal.ring2.phaseList;
        
        int ring1BarrierTime=0;
        for (int i=0; i<ring1PhaseList.count; i++) {
            SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
            if ([phase.barrier intValue]==1) {
                int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
                int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
                int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
                ring1BarrierTime=ring1BarrierTime+greenPhaseLength+yellowPhaseLength+allRedPhaseLength;
            }
        }
        ring1BarrierTime=ring1BarrierTime+TIMING_RING1_GRAPH_INITIAL_POSITION_X;
        int ring2BarrierTime=0;
        for (int i=0; i<ring2PhaseList.count; i++) {
            SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
            if ([phase.barrier intValue]==1) {
                int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
                int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
                int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
                ring2BarrierTime=ring2BarrierTime+greenPhaseLength+yellowPhaseLength+allRedPhaseLength;
            }
        }
        ring2BarrierTime=ring2BarrierTime+TIMING_RING2_GRAPH_INITIAL_POSITION_X;
        double barrierTime=0;
        if (ring1BarrierTime>=ring2BarrierTime) {
            barrierTime=ring1BarrierTime;
        }else{
            barrierTime=ring2BarrierTime;
        }
        int barrierPositionX=barrierTime;
        
        self.timingRing1GraphPositionX=TIMING_RING1_GRAPH_INITIAL_POSITION_X;
        int timingGraphPositionY=TIMING_RING1_GRAPH_POSITION_Y;
        int timingGraphHeight=TIMING_RING1_GRAPH_HEIGHT;
        for (int i=0; i<ring1PhaseList.count; i++) {
            SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
            if ([phase.barrier intValue]==2 && self.timingRing1GraphPositionX<barrierPositionX) {
                self.timingRing1GraphPositionX=barrierPositionX;
            }
            int greenPhaseLength=300*[phase.greenTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            int yellowPhaseLength=300*[phase.yellowTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            int allRedPhaseLength=300*[phase.allRedTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
            greenLabel.tag=100+i;
            greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
            greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
            greenLabel.textAlignment = UITextAlignmentCenter;
            greenLabel.backgroundColor = [UIColor greenColor];
            greenLabel.textColor=[UIColor darkGrayColor];  
            [self addLabelResponder:greenLabel];
            [self.labelList addObject:greenLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+greenPhaseLength;
            
            UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
            yellowLabel.backgroundColor = [UIColor yellowColor];      
            
            [self.labelList addObject:yellowLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+yellowPhaseLength;
            
            UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
            allRedLabel.backgroundColor = [UIColor redColor];      
            
            [self.labelList addObject:allRedLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+allRedPhaseLength;
        }
        {
            UILabel *barrierLabel = [[[UILabel alloc] initWithFrame:CGRectMake(barrierPositionX,timingGraphPositionY,5,timingGraphHeight+10)] autorelease];
            barrierLabel.backgroundColor = [UIColor blackColor];
            barrierLabel.tag=300;
            [self.labelList addObject:barrierLabel];
            [self.view addSubview:barrierLabel];
        }
        
        
        self.timingRing2GraphPositionX=TIMING_RING2_GRAPH_INITIAL_POSITION_X;
        timingGraphPositionY=TIMING_RING2_GRAPH_POSITION_Y;
        timingGraphHeight=TIMING_RING2_GRAPH_HEIGHT;
        for (int i=0; i<ring2PhaseList.count; i++) {
            SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
            if ([phase.barrier intValue]==2 && self.timingRing2GraphPositionX<barrierPositionX) {
                self.timingRing2GraphPositionX=barrierPositionX;
            }
            int greenPhaseLength=300*[phase.greenTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            int yellowPhaseLength=300*[phase.yellowTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            int allRedPhaseLength=300*[phase.allRedTime doubleValue]/[self.signalCycleLengthField.text doubleValue];
            UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
            greenLabel.tag=200+i;
            greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
            greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
            greenLabel.textAlignment = UITextAlignmentCenter;
            greenLabel.backgroundColor = [UIColor greenColor];
            greenLabel.textColor=[UIColor darkGrayColor];  
            [self addLabelResponder:greenLabel];
            [self.labelList addObject:greenLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+greenPhaseLength;
            
            UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
            yellowLabel.backgroundColor = [UIColor yellowColor];      
            
            [self.labelList addObject:yellowLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+yellowPhaseLength;
            
            UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
            allRedLabel.backgroundColor = [UIColor redColor];      
            
            [self.labelList addObject:allRedLabel];
            [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
            self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+allRedPhaseLength;
        }
        {
            UILabel *barrierLabel = [[[UILabel alloc] initWithFrame:CGRectMake(barrierPositionX,timingGraphPositionY,5,timingGraphHeight)] autorelease];
            barrierLabel.backgroundColor = [UIColor blackColor];
            barrierLabel.tag=300;
            [self.labelList addObject:barrierLabel];
            [self.view addSubview:barrierLabel];
        }
        
    }
    [self.view setNeedsDisplay];
}


#pragma mark -
#pragma mark PickerView DataSource

- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
    return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
    switch (component) {
        case 0:
        {
            NSMutableArray *mutableArray=[[[NSMutableArray alloc] init] autorelease];
            [mutableArray addObject:@""];
            for (SignalPhase * phase in self.signal.ring1.phaseList) {
                [mutableArray addObject:phase.phaseID];
            }
            for (SignalPhase * phase in self.signal.ring2.phaseList) {
                [mutableArray addObject:phase.phaseID];
            }
            return [mutableArray count];
        }
            break;
        case 1:
        {
            return [self.beginOrEndArray count];
        }
            break;
            
        default:
            break;
    }
//    NSMutableArray *mutableArray=[[[NSMutableArray alloc] init] autorelease];
//    for (SignalPhase * phase in self.signal.ring1.phaseList) {
//        [mutableArray addObject:phase.phaseID];
//    }
//    for (SignalPhase * phase in self.signal.ring2.phaseList) {
//        [mutableArray addObject:phase.phaseID];
//    }
//    return [mutableArray count];
    return 0;
}
- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component
{
    switch (component) {
        case 0:
        {
            NSMutableArray *mutableArray=[[[NSMutableArray alloc] init] autorelease];
            [mutableArray addObject:@""];
            for (SignalPhase * phase in self.signal.ring1.phaseList) {
                [mutableArray addObject:phase.phaseID];
            }
            for (SignalPhase * phase in self.signal.ring2.phaseList) {
                [mutableArray addObject:phase.phaseID];
            }
            return [mutableArray objectAtIndex:row];
        }
            break;
        case 1:
        {
            return [self.beginOrEndArray objectAtIndex:row];
        }
            break;
            
        default:
            break;
    }
    return @"";
} 

#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
      inComponent:(NSInteger)component
{
    switch (component) {
        case 0:
        {
            NSMutableArray *mutableArray=[[[NSMutableArray alloc] init] autorelease];
            [mutableArray addObject:@""];
            for (SignalPhase * phase in self.signal.ring1.phaseList) {
                [mutableArray addObject:phase.phaseID];
            }
            for (SignalPhase * phase in self.signal.ring2.phaseList) {
                [mutableArray addObject:phase.phaseID];
            }
            self.signal.offsetPhase=[mutableArray objectAtIndex:row];
            
            
        }
            break;
        case 1:
        {
            self.signal.offsetBorE=[self.beginOrEndArray objectAtIndex:row];
            
        }
            break;
            
        default:
            break;
    }
    [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
}

- (IBAction) selectOffSetPhase:(id)sender
{
    
    self.navigationItem.rightBarButtonItem = nil;
    [self.phasePicker setHidden:YES];
    self.title=@"Edit Signal";
    if (self.signal.offsetPhase==nil||[self.signal.offsetPhase isEqualToString:@""]) {
        self.phaseOffSetText.text=@"";
    }else {
        self.phaseOffSetText.text=[NSString stringWithFormat:@"Phase %@  %@",self.signal.offsetPhase,self.signal.offsetBorE];
    }
}
- (IBAction)clickMapButton:(id)sender {
    SignalLocationEditMapViewController *detailViewController=[[[SignalLocationEditMapViewController alloc] initWithNibNameAndSignal:@"SignalLocationEditMapViewController" signal:self.signal agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern bundle:nil] autorelease];
    //    self.navigationItem.titleView=nil;
    //    [self.imageView removeFromSuperview];
    //    self.navigationItem.title=@"Home";
    [detailViewController setTitle:self.signal.signalName];
    [self.navigationController pushViewController:detailViewController animated:YES];
}

- (void) goToSignalCounting:(id)sender
{
    SignalCountingViewController *detailViewController=[[[SignalCountingViewController alloc] initWithNibName:@"SignalCountingViewController" bundle:nil agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern signal:self.signal] autorelease];
    [detailViewController setTitle:@"Manually Counting Signal"];
    [self.navigationController pushViewController:detailViewController animated:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
@end
